package pl.un4giv3n.mightvsmagic.action.clan;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.entity.Clan;
import pl.un4giv3n.mightvsmagic.entity.ClanWar;
import pl.un4giv3n.mightvsmagic.utils.ClanUtil;

public class EndClanWarAction extends ClanAction{

	private static final long serialVersionUID = 1L;
	private Long warId;
	private ClanWar war;

	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		if(!validateData(entityManager)){
			entityManager.close();
			return ERROR;
		}
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		war.setFinished(true);
		Clan winner = getWinner(entityManager);
		Clan looser = getLooser(entityManager);
		war.setWinnerId(winner.getId());
		war.setWinnerName(winner.getName());
		long goldMove = looser.getGold()/10;
		war.setGold(goldMove);
		winner.addGold(goldMove);
		looser.removeGold(goldMove);
		entityManager.merge(war);
		entityManager.merge(winner);
		entityManager.merge(looser);
		entityManager.flush();
		transaction.commit();
		entityManager.close();
		return SUCCESS;
	}

	private Clan getWinner(EntityManager em) {
		return em.find(Clan.class, ClanUtil.getAttackerWins(war) > ClanUtil.getDefenderWins(war) ? war.getAttackerId() : war.getDefenderId());
	}
	private Clan getLooser(EntityManager em) {
		return em.find(Clan.class, ClanUtil.getAttackerWins(war) > ClanUtil.getDefenderWins(war) ? war.getDefenderId() : war.getAttackerId());
	}

	
	private boolean validateData(EntityManager entityManager) {
		boolean valid = true;
		clan = user.getClan();
		if(clan == null ){
			addActionError("Wybrany klan nie istnieje");
			valid = false;
		}
		if(warId == null){
			addActionError("Nieprawidłowe ID wojny");
			valid = false;
		}else{
			war = entityManager.find(ClanWar.class, warId);
			if(war == null){
				addActionError("Nieprawidłowe ID wojny");
				valid = false;
			}else{
				if(war.getBattles().size() < 5){
					addActionError("Stoczono zbyt mało bitw by zakończyć tą wojnę");
					valid = false;
				}
			}
		}
		return valid;
	}

	public Long getWarId() {
		return warId;
	}

	public void setWarId(Long warId) {
		this.warId = warId;
	}

}
